package daily_dao

import (
	"go_server/game_server/database/mysql"
	"go_server/zinx/zlog"
	"go_server/zinx/zutils"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type Daily struct {
	DateKey               string                                `gorm:"column:date_key"`
	RoleId                int64                                 `gorm:"column:role_id"`
	DailyTask             datatypes.JSONType[map[int32][]int32] `gorm:"column:daily_task"`
	Active                int32                                 `gorm:"column:active"`
	ChestInfo             datatypes.JSONSlice[int32]            `gorm:"column:chest_info"`
	HeroSummonUseFreeTime datatypes.JSONType[map[int32]int32]   `gorm:"column:hero_summon_use_free_time"`
	HeroSummonTimes       datatypes.JSONType[map[int32]int32]   `gorm:"column:hero_summon_times"`
	MarketItemInfo        datatypes.JSONType[map[int32]int32]   `gorm:"column:market_item_info"`
}

func (Daily) TableName() string {
	return "daily"
}

var (
	all_daily_field = zutils.GetGormFields(Daily{})
)

func GetDailyByDateKey(DateKey string, RoleId int64, fields ...[]string) *Daily {
	db := mysql.GetServerDBConnection()
	var daily Daily

	var selectFields []string

	if len(fields) > 0 {
		selectFields = fields[0]
	} else {
		selectFields = all_daily_field
	}

	if err := db.Select(selectFields).Where("date_key = ? and role_id = ?", DateKey, RoleId).First(&daily).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetDailyByDateKey ERR!!! DateKey: %d, RoleId: %s, err: %v", DateKey, RoleId, err)
		}
		return nil
	}
	return &daily
}

func UpdateDailyByDateKey(daily *Daily, fields []string) {
	if daily.DailyTask.Data() == nil {
		dailyTask := make(map[int32][]int32)
		daily.DailyTask = datatypes.NewJSONType(dailyTask)
	}

	if daily.ChestInfo == nil {
		chestInfo := make([]int32, 0)
		daily.ChestInfo = chestInfo
	}

	if daily.HeroSummonUseFreeTime.Data() == nil {
		heroSummonUseFreeTime := make(map[int32]int32)
		daily.HeroSummonUseFreeTime = datatypes.NewJSONType(heroSummonUseFreeTime)
	}

	if daily.HeroSummonTimes.Data() == nil {
		heroSummonTimes := make(map[int32]int32)
		daily.HeroSummonTimes = datatypes.NewJSONType(heroSummonTimes)
	}

	if daily.MarketItemInfo.Data() == nil {
		marketItemInfo := make(map[int32]int32)
		daily.MarketItemInfo = datatypes.NewJSONType(marketItemInfo)
	}

	db := mysql.GetServerDBConnection()

	if err := db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "date_key"}, {Name: "role_id"}},
		DoUpdates: clause.AssignmentColumns(fields),
	}).Create(daily).Error; err != nil {
		zlog.Errorf("create or update daily %v data failed: %v", daily, err)
	}
}
